import 'virtual:uno.css';
import 'ant-design-vue/dist/antd.less';
import '@/assets/style/antd.less';
import '@/assets/style/base.less';
import '@/assets/style/index.less';
import '@/assets/style/common.less'; // 子页面内部自定义公共样式
import '@/assets/icons/iconfont.css'; // icon样式
import App from './App.vue';
import Antd from 'ant-design-vue';
import router from './router';
import { createApp } from 'vue';
import { setupStore } from '@/store';
import { setupGlobDirective } from './directives';
import { setupGlobFun } from '@/mixins';
// import { setupI18n } from "./plugins/vue-i18n@9";

//查看图片
import 'viewerjs/dist/viewer.css';
import VueViewer from 'v-viewer';

import { useUserStoreWithOut } from '@/store/modules/user';
const userStore = useUserStoreWithOut();

//乾坤
// import mountApps from "@/micro";  //当为主应用时开启
import { renderWithQiankun, qiankunWindow, QiankunProps } from 'vite-plugin-qiankun/dist/helper';
import actions from '@/micro/shared/actions';

let app = null;

async function init(name: any = '#main-app', props: any) {
  // 创建应用实例
  app = createApp(App);
  //注册全局指令
  setupGlobDirective(app);

  //注册国际化
  // setupI18n(app);

  //注入全局函数
  setupGlobFun(app, props);

  //全局注入antd
  app.use(Antd);

  //图片查看器
  app.use(VueViewer);

  //注册状态管理
  // app.use(store);
  setupStore(app);
  // app.use(createPinia());

  //注册路由
  app.use(router);

  //当路由准备好时在执行挂载( https://next.router.vuejs.org/api/#isready)
  await router.isReady();
  app.mount(name);
}

const render = (props: QiankunProps = {}) => {
  let container = null;
  if (props) {
    container = props.container;
    // 注入 actions 实例
    // actions.setActions(props);
    if (props.shared) {
      actions.onGlobalStateChange = props.shared.onGlobalStateChange;
      actions.setGlobalState = props.shared.setGlobalState;
      actions.updateState = props.shared.updateState;
    }
    actions.onGlobalStateChange((state: any, prev: any) => {
      console.log('父级的token', state);
      if (state && state.token) {
        userStore.setToken(state.token);
      }
    }, true);
  }

  const app: string | Element = container?.querySelector('#dmsStorage') || '#dmsStorage'; // 避免id重复导致微应用挂载失败
  init(app, props);
};

const initQianKun = () => {
  renderWithQiankun({
    bootstrap() {
      console.log('微应用：bootstrap');
    },
    mount(props) {
      // 获取主应用传入数据
      console.log('微应用：mount', props);
      fixStyleBug();
      render(props);
    },
    unmount(props) {
      console.log('微应用：unmount', props);
      app.unmount();
      app._container.innerHTML = '';
      app = null;
    },
    update(props) {
      console.log('微应用：update', props);
    }
  });
};

qiankunWindow.__POWERED_BY_QIANKUN__ ? initQianKun() : render(); // 判断是否使用 qiankun ，保证项目可以独立运行

router.afterEach(() => {
  if (qiankunWindow.__POWERED_BY_QIANKUN__) {
    fixStyleBug();
  }
});
let styleCount = 0,
  styleList = [];

// 定义styleDisappearedRecord，表明styleList哪一段部分保存的是已丢失的<style>
const styleDisappearedRecord = { start: 0, end: 0 };
function fixStyleBug() {
  const qiankunStyles = document.querySelectorAll('div[data-qiankun="dms-web"] style');
  const len = qiankunStyles.length;
  if (styleCount < len) {
    const originalArr = Array.from(qiankunStyles); // 原始数组
    /* 
      调整丢失的<style>与框架新加的<style>的位置，使得丢失的<style>总是位于数组最后，以便与框架的dynamicStyleSheetElements数组保持对应
      即styleList = [...[未丢失样式], ...[新页面新增样式], ...[丢失样式]]  防止把要添加的<style>误加成新<style>
      */
    styleCount = len;
    styleList = [
      ...originalArr.slice(0, styleDisappearedRecord.start),
      ...originalArr.slice(styleDisappearedRecord.end),
      ...originalArr.slice(styleDisappearedRecord.start, styleDisappearedRecord.end)
    ];
  } else if (styleCount > len) {
    const container = document.querySelectorAll('div[data-qiankun="dms-web"]')[0];
    styleDisappearedRecord.start = styleCount - len + 1;
    styleDisappearedRecord.end = styleCount;
    styleList.forEach((style, index) => {
      // 丢失的样式都是从后面开始消失的，所以对比长度，添加上遗漏的
      if (index > len - 1) {
        container.appendChild(style);
      }
    });
  }
}
